#include "Socket.hpp"
#include <iostream>
#include "Protocol.hpp"
#include <string>
#include <time.h>
#include <assert.h>
static void Usage(const std::string& proc)
{
    std::cout << "\nUsage:" << proc << " serverip serverport\n\n" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    Sock sockfd;
    sockfd.Socket();
    bool r = sockfd.Connect(serverip, serverport);
    if(!r) 
    {
        return 1;
    }
    
    srand(time(nullptr)^getpid());
    std::string opers = "+-*/%=-=&:><";
    int cnt = 1;
    std::string inbuffer_stream;
    while(cnt)
    {
        if(cnt > 10) break;
        cout << "----------------------------" << endl;
        std::cout << "第" << cnt++ << "次测试..." << std::endl; 
        int x = rand()%100 + 1;
        usleep(1234);
        int y = rand()%100;
        usleep(6546);
        char op = opers[rand()%opers.size()];
        Request req(x, y, op);
        req.DebugPrint();

        std::string package;
        req.Serialize(&package);
        package = Encode(package);
        std::cout << "这是最新的发出去的请求: \n" << package << std::endl; 
        write(sockfd.Fd(), package.c_str(), package.size());
        // write(sockfd.Fd(), package.c_str(), package.size());
        // write(sockfd.Fd(), package.c_str(), package.size());
        // write(sockfd.Fd(), package.c_str(), package.size());
        char buffer[128];
        ssize_t n = read(sockfd.Fd(), buffer, sizeof(buffer)); //无法保证读到一个完整的报文
        if(n > 0)
        {
            buffer[n] = 0;
            inbuffer_stream += buffer;
            std::string content;
            bool r = Decode(inbuffer_stream, &content);
            assert(r); //这里我们简单一点，不考虑不完整的情况了
            Response resp;
            r = resp.Deserialize(content);
            assert(r);
            resp.DebugPrint();
        }
        sleep(1);
    }
    
    sockfd.Close();
    return 0;
}